﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;

using Mr.LinqToWeibo.SearchCriteria;

namespace Mr.LinqToWeibo
{
	public class QueryableWeiboData<T>
        : IQueryableWeiboData<T>
	{
		public QueryableWeiboData ()
		{
            this.Provider = new WeiboDataQueryProvider<T>();
			this.Expression = Expression.Constant (this);
		}

        internal QueryableWeiboData(IWeiboDataQueryProvider<T> provider, Expression expression)
		{
			if (provider == null) {
				throw new ArgumentNullException ("provider");
			}

			if (expression == null) {
				throw new ArgumentNullException ("expression");
			}

			this.Provider = provider;
			this.Expression = expression;
		}

		public Type ElementType {
			get { return typeof(T); }
		}

		public Expression Expression { get; private set; }

		IEnumerator IEnumerable.GetEnumerator ()
		{
			return (this.Provider.Execute<IEnumerable> (this.Expression)).GetEnumerator ();
		}

		public IEnumerator<T> GetEnumerator ()
		{
			return (this.Provider.Execute<IEnumerable<T>> (Expression)).GetEnumerator ();
		}

        #region IQueryableWeiboData<TEntity> Members

        public IWeiboDataQueryProvider<T> Provider { get; set; }

		IQueryProvider IQueryable.Provider {
			get {
				return this.Provider;
			}
		}

		public void SetWeiBoScope (Scope scope)
		{
			this.Provider.WeiBoScope = scope;
		}
		
		public void SetAccessTokenAndSecret (string accessToken, string secret)
		{
			if (string.IsNullOrEmpty (accessToken) ||
				string.IsNullOrEmpty (secret)) {
				throw new ArgumentNullException ("accessToken or secret");
			}
			this.Provider.AccessToken = accessToken;
			this.Provider.AccessTokenSecret = secret;
		}
		
        #endregion
	}
}
